package cn.mjnxin.iot.gate.coder;

import cn.mjnxin.iot.base.domain.ChannelData;
import cn.mjnxin.iot.base.domain.SocketData;
import cn.mjnxin.iot.base.domain.TerminalRepacker;
import cn.mjnxin.iot.base.log.LogWorker;
import cn.mjnxin.iot.base.util.CommonUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
/**
 * 编码器 将对象 编码成字节数组  --->目的地是终端硬件

 * @author CLG 2023年10月10日
 * @version V1.0.0
 */
public class Gate2TerminalEncoder extends MessageToByteEncoder<ChannelData>{
	// 日志等级 0：无日志 1：报文长度日志 2：报文内容日志 3：所有日志
	private int logLevel = 0;

	private TerminalRepacker repacker;
	
	public Gate2TerminalEncoder(int logLevel, TerminalRepacker repacker) {
		this.logLevel  = logLevel;
		this.repacker = repacker;
	}
	
    @Override
    protected void encode(ChannelHandlerContext ctx, ChannelData msg, ByteBuf out) throws Exception {
        try {
            SocketData data = msg.getSocketData();
            if (logLevel == 1) {
            	if(msg.getHostAddress() == null) {
            		LogWorker.logForce(String.format("%d|G->T[%s]=%d Bytes", msg.getPid(), msg.getTerminalAddress(), out.readableBytes()));
            	}
            	else {
            		LogWorker.logForce(String.format("%d|H[%s]->G->T[%s]=%d Bytes", msg.getPid(), msg.getHostAddress(), msg.getTerminalAddress(), out.readableBytes()));            		
            	}
            }
            else if (logLevel >= 2) {
            	if(msg.getHostAddress() == null) {
            		LogWorker.logForce(String.format("%d|G->T[%s]=", msg.getPid(), msg.getTerminalAddress()), data.getByteBuf());
            	}
            	else {
            		LogWorker.logForce(String.format("%d|H[%s]->G->T[%s]=", msg.getPid(), msg.getHostAddress(), msg.getTerminalAddress()), data.getByteBuf());            		
            	}
            }
            ByteBuf byteBuf = data.getByteBuf();
            if (repacker != null) {
            	byteBuf = repacker.repackBefore2Terminal(byteBuf);
            }
			out.writeBytes(byteBuf);
        }finally {
            CommonUtil.releaseData(msg);
        }
    }
}
